package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param roleDto
     * @return
     */
    @Override
    public PageResponse<RoleVo> selectPage(Integer pageNum, Integer pageSize, RoleDto roleDto) {
        PageHelper.startPage(pageNum,pageSize);
        Page<Role> roles = roleMapper.selectPage(roleDto);
        return PageResponse.of(roles,RoleVo.class);
    }

    /**
     * 添加角色
     * @param roleDto
     */
    @Override
    public void createRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    /**
     * 查询当前角色对应的资源数据
     * @param roleId
     * @return
     */
    @Override
    public Set<String> selectCheckedResource(Long roleId) {
        return roleResourceMapper.selectResourceNoByRoleId(roleId);
    }

    /**
     * 修改角色
     * @param roleDto
     */
    @Override
    public Boolean updateRole(RoleDto roleDto) {
        //对象拷贝
        Role role = BeanUtil.toBean(roleDto, Role.class);

        //TODO 如果当前的操作是禁用，角色被用户引用之后，不能禁用  已完成
        if (ObjectUtil.isNotEmpty(role.getDataState()) && role.getDataState().equals("1")) {
            if (countUserRoleByRoleId(role.getId()) > 0) {
                throw new RuntimeException("该角色已分配用户,不能禁用");
            }
        }


        roleMapper.updateByPrimaryKeySelective(role);

        //判断是否包含资源数据
        if(ObjectUtil.isEmpty(roleDto.getCheckedResourceNos())){
            return true;
        }

        //删除当前角色对应的资源数据
        roleResourceMapper.deleteByRoleId(role.getId());

        //组装数据
        String[] checkedResourceNos = roleDto.getCheckedResourceNos();
        List<RoleResource> roleResourceList = new ArrayList<>();
        Arrays.stream(checkedResourceNos).forEach(resourceNo->{
            RoleResource roleResource = RoleResource.builder()
                    .resourceNo(resourceNo)
                    .roleId(role.getId())
                    .dataState(SuperConstant.DATA_STATE_0).build();
            roleResourceList.add(roleResource);
        });
        //判断组装之后是否为空
        if(EmptyUtil.isNullOrEmpty(roleResourceList)){
            return true;
        }
        //批量保存
        roleResourceMapper.batchInsert(roleResourceList);
        return true;
    }

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    public int countUserRoleByRoleId(Long roleId) {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    /**
     * 删除角色
     * @param roleId
     */
    @Override
    public void deleteByRoleId(Long roleId) {
        //TODO 判断  如果该角色已分配用户,不能删除  已完成
        if (countUserRoleByRoleId(roleId) > 0) {
            throw new BaseException(BasicEnum.ROLE_DISTRIBUTED);
        }

        roleMapper.deleteByPrimaryKey(roleId);
        roleResourceMapper.deleteByRoleId(roleId);

    }

    /***
     *  角色下拉框
     * @return
     */
    @Override
    public List<RoleVo> initRoles() {
        List<Role> roleList = roleMapper.initRoles();
        return BeanUtil.copyToList(roleList,RoleVo.class);
    }
}
